<?php

namespace app\shopapi\model;

use think\Db;
use think\Loader;
use think\Model;
use traits\model\SoftDelete;

class ShopGoods extends Model
{

    use SoftDelete;

    

    // 表名
    protected $name = 'shop_goods';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'start_sell_time_text',
        'end_sell_time_text',
        //'start_may_use_time_text',
        //'end_may_use_time_text',
        //'start_use_time_text',
        //'end_use_time_text'
    ];
    

    



    public function getStartSellTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['start_sell_time']) ? $data['start_sell_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getEndSellTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['end_sell_time']) ? $data['end_sell_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    /*public function getStartMayUseTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['start_may_use_time']) ? $data['start_may_use_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }*/


    /*public function getEndMayUseTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['end_may_use_time']) ? $data['end_may_use_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }*/


/*    public function getStartUseTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['start_use_time']) ? $data['start_use_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getEndUseTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['end_use_time']) ? $data['end_use_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }*/

    protected function setStartSellTimeAttr($value)
    {
        return $value === '' ? 0 : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setEndSellTimeAttr($value)
    {
        return $value === '' ? 0 : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    /*protected function setStartMayUseTimeAttr($value)
    {
        return $value === '' ? 0 : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setEndMayUseTimeAttr($value)
    {
        return $value === '' ? 0 : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }*/

/*    protected function setStartUseTimeAttr($value)
    {
        return $value === '' ? 0 : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setEndUseTimeAttr($value)
    {
        return $value === '' ? 0 : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }*/


    public function user()
    {
        return $this->belongsTo('User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function shop()
    {
        return $this->belongsTo('app\admin\model\Shop', 'shop_id', 'shop_id', [], 'LEFT')->setEagerlyType(0);
    }


    public function category()
    {
        return $this->belongsTo('app\admin\model\shop\goods\Category', 'goods_category_id', 'category_id', [], 'LEFT')->setEagerlyType(0);
    }

    //删除
    public function del($goods_id)
    {
        $detail = ShopGoods::where(['goods_id'=>$goods_id])->find();
        $res = $detail->delete();
        return $res;
    }

    //修改商品状态
    public function updateGoodsState($goods_id,$state)
    {
        $goods_info = ShopGoods::get($goods_id);

        if ($state==1){
            if (empty($goods_info['profile']))throw new \Exception('请填写套餐项目名称');
            if (empty($goods_info['images']))throw new \Exception('请上传图片');
            if (empty($goods_info['sku']))throw new \Exception('请填写套餐分组');
            if (empty($goods_info['price']))throw new \Exception('请填写团购价');
        }

        if ($goods_info['goods_state']==$state)throw new \Exception('操作异常');

        if ($state==1){
            Shop::where(['shop_id'=>$goods_info['shop_id']])->setInc('line_goods_num',1);
        } else {
            Shop::where(['shop_id'=>$goods_info['shop_id']])->setDec('line_goods_num',1);
        }
        $res = ShopGoods::where(['goods_id'=>$goods_id])->update(['goods_state' => $state]);

        return $res;
    }

    //团购列表
    public function lists($params)
    {
        $orderby = $params['orderby'];
        $sort = $params['sort'];
        $status = $params['status'];
        $pageNum = 15;
        if (isset($params['num']) && !empty($params['num'])) {
            $pageNum = $params['num'];
        }
        $keyword = $params['keyword'];
        $where = ['shop_id'=>$params['shop_id']];
        if(!empty($keyword)){
            $where['goods_name'] = ['like',"%$keyword%"];
        }

        if ($orderby=='createtime'){
            $order = 'createtime '.$sort;
        } elseif ($orderby=='sale'){
            $order = 'sale '.$sort;
        } elseif ($orderby=='verify_num'){
            $order = 'verify_num '.$sort;
        } else {
            $order = 'createtime desc';
        }

        if ($status!='all'){
            $where['goods_state'] = $status;
        }

        $lists = ShopGoods::where($where)
            ->order($order)
            ->field('goods_id,shop_id,goods_name,profile,goods_category_name,goods_state,sale,sale_price,verify_num')
            ->paginate($pageNum, false, ['query' => request()->get()]);

        return $lists;
    }

    //团购草稿
    public function draft($params)
    {
        Db::startTrans();

        try {
            $model = new ShopGoods();

            $line_price = 0;
            if (array_key_exists('sku',$params)){
                $sku = _json_decode($params['sku']);
                foreach ($sku as $k=>$v){
                    foreach ($v['sku'] as $kk=>$vv){
                        $line_price+=$vv['price']*$vv['num'];
                    }
                }
                $sku = json_encode($sku,320);
            } else {
                $sku = '';
            }

            $data = [
                'shop_id'=>$params['shop_id'],
                'user_id'=>$params['user_id'],
                'goods_category_id'=>array_key_exists('goods_category_id',$params)?$params['goods_category_id']:'',//套餐类型id
                'goods_category_name'=>array_key_exists('goods_category_name',$params)?$params['goods_category_name']:'',//套餐类型名称
                'profile'=>array_key_exists('profile',$params)?$params['profile']:'',//套餐项目
                'goods_name'=>array_key_exists('goods_name',$params)?$params['goods_name']:'',//套餐名称
                'use_people_type'=>array_key_exists('use_people_type',$params)?$params['use_people_type']:'',//使用人数,0:单人,1:双人,2:3-4人,3:5-6人,4:不限人数,5自定义
                'start_use_people'=>array_key_exists('start_use_people',$params)?$params['start_use_people']:'',
                'end_use_people'=>array_key_exists('end_use_people',$params)?$params['end_use_people']:'',
                'images'=>array_key_exists('images',$params)?$params['images']:'',//套餐图片
                'sku'=>$sku,//商品sku
                'detail'=>array_key_exists('detail',$params)?$params['detail']:'',//图文详情图片
                'stock_type'=>array_key_exists('stock_type',$params)?$params['stock_type']:'',//库存类型,0不限,1限制最多
                'stock'=>array_key_exists('stock',$params)?$params['stock']:'',//限制最多总库存
                'every_stock_type'=>array_key_exists('every_stock_type',$params)?$params['every_stock_type']:'',//每日库存类型0不限,1限制最多
                'every_stock'=>array_key_exists('every_stock',$params)?$params['every_stock']:'',//限制最多每日库存
                'everyone_everyday_buy_type'=>array_key_exists('everyone_everyday_buy_type',$params)?$params['everyone_everyday_buy_type']:'',//每人每日最多购买类型,0不限,1限制最多
                'everyone_everyday_buy'=>array_key_exists('everyone_everyday_buy',$params)?$params['everyone_everyday_buy']:'',//限制最多每人每日最多购买
                'start_sell_time_type'=>array_key_exists('start_sell_time_type',$params)?$params['start_sell_time_type']:'',//开始售卖时间类型,0发布立即上线,1选择开始时间
                'start_sell_time'=>array_key_exists('start_sell_time',$params)?$params['start_sell_time']:'',//开始售卖时间
                'end_sell_time'=>array_key_exists('end_sell_time',$params)?$params['end_sell_time']:'',//结束售卖时间
                'auto_continue_sell'=>array_key_exists('auto_continue_sell',$params)?$params['auto_continue_sell']:'',//1是到期自动延续30天
                'start_may_use_time'=>array_key_exists('start_may_use_time',$params)?$params['start_may_use_time']:'',//可用时间的开始日期
                'end_may_use_time'=>array_key_exists('end_may_use_time',$params)?$params['end_may_use_time']:'',//可用时间的结束日期
                'may_use_time_type'=>array_key_exists('may_use_time_type',$params)?$params['may_use_time_type']:'',//可用时间类型0固定有效期,1购买后*天有效
                'may_use_time_day'=>array_key_exists('may_use_time_day',$params)?$params['may_use_time_day']:'',//购买后*天有效
                'use_date_type'=>array_key_exists('use_date_type',$params)?$params['use_date_type']:'',//使用日期类型0所有日期可用,1部分日期可用
                'use_date'=>array_key_exists('use_date',$params)?$params['use_date']:'',//0是周日,1-6表示周一到周六,7节假日通用,8节假日不可用
                'use_time_type'=>array_key_exists('use_time_type',$params)?$params['use_time_type']:'',//使用时间类型,0营业时间可用,1部分时间可用
                'start_use_time'=>array_key_exists('start_use_time',$params)?$params['start_use_time']:'',//使用时间的部分时间的开始时间
                'end_use_time'=>array_key_exists('end_use_time',$params)?$params['end_use_time']:'',//使用时间的部分时间的结束时间
                'subscribe_type'=>array_key_exists('subscribe_type',$params)?$params['subscribe_type']:'',//是否预约,0无需预约,1需提前预约*小时
                'subscribe_hour'=>array_key_exists('subscribe_hour',$params)?$params['subscribe_hour']:'',//提前预约时间
                'coupon_limited'=>array_key_exists('coupon_limited',$params)?$params['coupon_limited']:'',//劵限用,0不限,1每人限用,2每桌限用
                'limited_num'=>array_key_exists('limited_num',$params)?$params['limited_num']:'',//劵限用数量
                'meal'=>array_key_exists('meal',$params)?$params['meal']:'',//堂食外卖约定0堂食,1外卖
                'privateroom_type'=>array_key_exists('privateroom_type',$params)?$params['privateroom_type']:'',//是否可用包间,0否1是,2详细咨询客服,3无
                'enjoy_preferential_type'=>array_key_exists('enjoy_preferential_type',$params)?$params['enjoy_preferential_type']:'',//同时享受店内其他优惠,0不可以,1可以,2详细咨询客服,3无
                'other_rule'=>array_key_exists('other_rule',$params)?$params['other_rule']:'',//其他规则补充
                'price'=>array_key_exists('price',$params)?$params['price']:'',//团购价
                'commission_rate'=>array_key_exists('commission_rate',$params)?$params['commission_rate']:'',//佣金率
                'line_price'=>$line_price,
            ];

            if (empty($data['goods_name']))throw new \Exception('请填写套餐名称');

            $res =  $model->save($data);

            if ($res){
                Db::commit();
                return $model->goods_id;
            } else {
                Db::rollback();
                throw new \Exception('保存失败');
            }
        } catch (\Exception $e) {
            Db::rollback();
            throw new \Exception($e->getMessage());
        }
    }


    //添加团购
    public function add($params)
    {
        Db::startTrans();

        try {
            $model = new ShopGoods();

            $sku = _json_decode($params['sku']);
            $line_price = 0;
            foreach ($sku as $k=>$v){
                foreach ($v['sku'] as $kk=>$vv){
                    $line_price+=$vv['price']*$vv['num'];
                }
            }
            $data = [
                'shop_id'=>$params['shop_id'],
                'user_id'=>$params['user_id'],
                'goods_category_id'=>$params['goods_category_id'],//套餐类型id
                'goods_category_name'=>$params['goods_category_name'],//套餐类型名称
                'profile'=>$params['profile'],//套餐项目
                'goods_name'=>$params['goods_name'],//套餐名称
                'use_people_type'=>$params['use_people_type'],//使用人数,0:单人,1:双人,2:3-4人,3:5-6人,4:不限人数,5自定义
                'start_use_people'=>$params['start_use_people'],
                'end_use_people'=>$params['end_use_people'],
                'images'=>$params['images'],//套餐图片
                'sku'=>json_encode($sku,320),//商品sku
                'detail'=>$params['detail'],//图文详情图片
                'stock_type'=>$params['stock_type'],//库存类型,0不限,1限制最多
                'stock'=>$params['stock'],//限制最多总库存
                'every_stock_type'=>$params['every_stock_type'],//每日库存类型0不限,1限制最多
                'every_stock'=>$params['every_stock'],//限制最多每日库存
                'everyone_everyday_buy_type'=>$params['everyone_everyday_buy_type'],//每人每日最多购买类型,0不限,1限制最多
                'everyone_everyday_buy'=>$params['everyone_everyday_buy'],//限制最多每人每日最多购买
                'start_sell_time_type'=>$params['start_sell_time_type'],//开始售卖时间类型,0发布立即上线,1选择开始时间
                'start_sell_time'=>$params['start_sell_time'],//开始售卖时间
                'end_sell_time'=>$params['end_sell_time'],//结束售卖时间
                'auto_continue_sell'=>$params['auto_continue_sell'],//1是到期自动延续30天
                'start_may_use_time'=>$params['start_may_use_time'],//可用时间的开始日期
                'end_may_use_time'=>$params['end_may_use_time'],//可用时间的结束日期
                'may_use_time_type'=>$params['may_use_time_type'],//可用时间类型0固定有效期,1购买后*天有效
                'may_use_time_day'=>$params['may_use_time_day'],//购买后*天有效
                'use_date_type'=>$params['use_date_type'],//使用日期类型0所有日期可用,1部分日期可用
                'use_date'=>$params['use_date'],//0是周日,1-6表示周一到周六,7节假日通用,8节假日不可用
                'use_time_type'=>$params['use_time_type'],//使用时间类型,0营业时间可用,1部分时间可用
                'start_use_time'=>$params['start_use_time'],//使用时间的部分时间的开始时间
                'end_use_time'=>$params['end_use_time'],//使用时间的部分时间的结束时间
                'subscribe_type'=>$params['subscribe_type'],//是否预约,0无需预约,1需提前预约*小时
                'subscribe_hour'=>$params['subscribe_hour'],//提前预约时间
                'coupon_limited'=>$params['coupon_limited'],//劵限用,0不限,1每人限用,2每桌限用
                'limited_num'=>$params['limited_num'],//劵限用数量
                'meal'=>$params['meal'],//堂食外卖约定0堂食,1外卖
                'privateroom_type'=>$params['privateroom_type'],//是否可用包间,0否1是,2详细咨询客服,3无
                'enjoy_preferential_type'=>$params['enjoy_preferential_type'],//同时享受店内其他优惠,0不可以,1可以,2详细咨询客服,3无
                'other_rule'=>$params['other_rule'],//其他规则补充
                'price'=>$params['price'],//团购价
                'commission_rate'=>$params['commission_rate'],//佣金率
                'line_price'=>$line_price,
            ];

            $validate = Loader::validate('ShopGoods');
            if(!$validate->check($data)){
                throw new \Exception($validate->getError());
            }

            $res =  $model->save($data);

            if ($res){
                Db::commit();
                return $model->goods_id;
            } else {
                Db::rollback();
                throw new \Exception('添加失败');
            }
        } catch (\Exception $e) {
            Db::rollback();
            throw new \Exception($e->getMessage());
        }
    }

    //编辑团购
    public function edit($params)
    {
        Db::startTrans();

        $line_price = 0;
        if (array_key_exists('sku',$params)){
            $sku = _json_decode($params['sku']);
            foreach ($sku as $k=>$v){
                foreach ($v['sku'] as $kk=>$vv){
                    $line_price+=$vv['price']*$vv['num'];
                }
            }
            $sku = json_encode($sku,320);
        } else {
            $sku = '';
        }

        try {
            //$model = new ShopGoods();
            $model = ShopGoods::get($params['goods_id']);

            $data = [
                'goods_category_id'=>$params['goods_category_id'],//套餐类型id
                'goods_category_name'=>$params['goods_category_name'],//套餐类型名称
                'profile'=>$params['profile'],//套餐项目
                'goods_name'=>$params['goods_name'],//套餐名称
                'use_people_type'=>$params['use_people_type'],//使用人数,0:单人,1:双人,2:3-4人,3:5-6人,4:不限人数,5自定义
                'start_use_people'=>$params['start_use_people'],
                'end_use_people'=>$params['end_use_people'],
                'images'=>$params['images'],//套餐图片
                'sku'=>$sku,//商品sku
                'detail'=>$params['detail'],//图文详情图片
                'stock_type'=>$params['stock_type'],//库存类型,0不限,1限制最多
                'stock'=>$params['stock'],//限制最多总库存
                'every_stock_type'=>$params['every_stock_type'],//每日库存类型0不限,1限制最多
                'every_stock'=>$params['every_stock'],//限制最多每日库存
                'everyone_everyday_buy_type'=>$params['everyone_everyday_buy_type'],//每人每日最多购买类型,0不限,1限制最多
                'everyone_everyday_buy'=>$params['everyone_everyday_buy'],//限制最多每人每日最多购买
                'start_sell_time_type'=>$params['start_sell_time_type'],//开始售卖时间类型,0发布立即上线,1选择开始时间
                'start_sell_time'=>$params['start_sell_time'],//开始售卖时间
                'end_sell_time'=>$params['end_sell_time'],//结束售卖时间
                'auto_continue_sell'=>$params['auto_continue_sell'],//1是到期自动延续30天
                'start_may_use_time'=>$params['start_may_use_time'],//可用时间的开始日期
                'end_may_use_time'=>$params['end_may_use_time'],//可用时间的结束日期
                'may_use_time_type'=>$params['may_use_time_type'],//可用时间类型0固定有效期,1购买后*天有效
                'may_use_time_day'=>$params['may_use_time_day'],//购买后*天有效
                'use_date_type'=>$params['use_date_type'],//使用日期类型0所有日期可用,1部分日期可用
                'use_date'=>$params['use_date'],//0是周日,1-6表示周一到周六,7节假日通用,8节假日不可用
                'use_time_type'=>$params['use_time_type'],//使用时间类型,0营业时间可用,1部分时间可用
                'start_use_time'=>$params['start_use_time'],//使用时间的部分时间的开始时间
                'end_use_time'=>$params['end_use_time'],//使用时间的部分时间的结束时间
                'subscribe_type'=>$params['subscribe_type'],//是否预约,0无需预约,1需提前预约*小时
                'subscribe_hour'=>$params['subscribe_hour'],//提前预约时间
                'coupon_limited'=>$params['coupon_limited'],//劵限用,0不限,1每人限用,2每桌限用
                'limited_num'=>$params['limited_num'],//劵限用数量
                'meal'=>$params['meal'],//堂食外卖约定0堂食,1外卖
                'privateroom_type'=>$params['privateroom_type'],//是否可用包间,0否1是,2详细咨询客服,3无
                'enjoy_preferential_type'=>$params['enjoy_preferential_type'],//同时享受店内其他优惠,0不可以,1可以,2详细咨询客服,3无
                'other_rule'=>$params['other_rule'],//其他规则补充
                'price'=>$params['price'],//团购价
                'commission_rate'=>$params['commission_rate'],//佣金率
                //'goods_state'=>$params['goods_state'],//0待发布,1已上架,2已下架,3已失效
            ];

            $validate = Loader::validate('ShopGoods');

            if(!$validate->check($data)){
                throw new \Exception($validate->getError());
            }

            $res =  $model->save($data);

            if ($res){
                Db::commit();
                return $model->goods_id;
            } else {
                Db::rollback();
                throw new \Exception('编辑失败');
            }
        } catch (\Exception $e) {
            Db::rollback();
            throw new \Exception($e->getMessage());
        }
    }
}
